<?php
/*********************************************************************************
 * The contents of this file are subject to the SugarCRM Public License Version 1.1.2
 * ("License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
 * Software distributed under the License is distributed on an  "AS IS"  basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 * The Original Code is:  SugarCRM Open Source
 * The Initial Developer of the Original Code is SugarCRM, Inc.
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.;
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 ********************************************************************************/



// Account is used to store vtiger_account information.
class Consignment extends CRMEntity {
	var $log;
	var $db;

	var $table_name = "vtiger_consignment";
	var $table_index= 'consignmentid';
	var $tab_name = Array('vtiger_crmentity','vtiger_consignment','vtiger_consignmentbillads','vtiger_consignmentshipads','vtiger_consignmentcf', 'vtiger_inventoryproductrel');
	var $tab_name_index = Array('vtiger_crmentity'=>'crmid','vtiger_consignment'=>'consignmentid','vtiger_consignmentbillads'=>'consignmentbilladdressid','vtiger_consignmentshipads'=>'consignmentshipaddressid','vtiger_consignmentcf'=>'consignmentid', 'vtiger_inventoryproductrel' => 'id');
	/**
	 * Mandatory table for supporting custom fields.
	 */
	var $customFieldTable = Array('vtiger_consignmentcf', 'consignmentid');
	
	var $column_fields = Array();

	var $update_product_array = Array();	

	var $sortby_fields = Array('subject','consignment_no','consignmentstatus','smownerid','accountname','lastname');

	// This is used to retrieve related vtiger_fields from form posts.
	var $additional_column_fields = Array('assigned_user_name', 'smownerid', 'opportunity_id', 'case_id', 'contact_id', 'task_id', 'note_id', 'meeting_id', 'call_id', 'email_id', 'parent_name', 'member_id' );

	// This is the list of vtiger_fields that are in the lists.
	var $list_fields = Array(
				'Consignment No'=>Array('consignment'=>'consignment_no'),
				'Subject'=>Array('consignment'=>'subject'),				
				'Sales Order'=>Array('consignment'=>'salesorderid'),
				'Status'=>Array('consignment'=>'consignmentstatus'),
				'Total'=>Array('consignment'=>'total'),
				'Assigned To'=>Array('crmentity'=>'smownerid')
				);
	
	var $list_fields_name = Array(
				        'Consignment No'=>'consignment_no',
						'Subject'=>'subject',						
				        'Sales Order'=>'salesorder_id',
				        'Status'=>'consignmentstatus',
				        'Total'=>'hdnGrandTotal',
				        'Assigned To'=>'assigned_user_id'
				      );
	var $list_link_field= 'subject';

	var $search_fields = Array(
				'Consignment No'=>Array('consignment'=>'consignment_no'),
				'Subject'=>Array('purchaseorder'=>'subject'),
				'Account Name'=>Array('contactdetails'=>'account_id'),
				'Created Date' => Array('crmentity'=>'createdtime'),
				'Assigned To'=>Array('crmentity'=>'smownerid'),
				);
	
	var $search_fields_name = Array(
				        'Consignment No'      =>'consignment_no',
						'Subject'             => 'subject',
						'Account Name'        => 'account_id',
						'Created Time'        => 'createdtime',
						'Assigned To'         => 'assigned_user_id'
				      );

        // For Popup window record selection
	var $popup_fields = Array('subject');

	// This is the list of vtiger_fields that are required.
	var $required_fields =  array("accountname"=>1);

	//Added these variables which are used as default order by and sortorder in ListView
	var $default_order_by = 'crmid';
	var $default_sort_order = 'ASC';

	var $mandatory_fields = Array('subject','createdtime' ,'modifiedtime', 'assigned_user_id', 'quantity', 'listprice', 'productid');
	var $_salesorderid;
	var $_recurring_mode;
	
	// For Alphabetical search
	var $def_basicsearch_col = 'subject';
        
	var $entity_table = "vtiger_crmentity";     

	// For workflows update field tasks is deleted all the lineitems.
	var $isLineItemUpdate = true;	
        
	/**	Constructor which will set the column_fields in this object
	 */
	function Consignment() {
		$this->log =LoggerManager::getLogger('Consignment');
		$this->log->debug("Entering Consignment() method ...");
		$this->db = PearDatabase::getInstance();
		$this->column_fields = getColumnFields('Consignment');
		$this->log->debug("Exiting Consignment method ...");
	}


    
	/** Function to handle the module specific save operations

	*/

	function save_module($module) {
		global $updateInventoryProductRel_deduct_stock;
		$updateInventoryProductRel_deduct_stock = true;

		/* $_REQUEST['REQUEST_FROM_WS'] is set from webservices script.
		 * Depending on $_REQUEST['totalProductCount'] value inserting line items into DB.
		 * This should be done by webservices, not be normal save of Inventory record.
		 * So unsetting the value $_REQUEST['totalProductCount'] through check point
		 */
		if (isset($_REQUEST['REQUEST_FROM_WS']) && $_REQUEST['REQUEST_FROM_WS']) {
			unset($_REQUEST['totalProductCount']);
		}
		//in ajax save we should not call this function, because this will delete all the existing product values
		if(isset($this->_recurring_mode) && $this->_recurring_mode == 'recurringconsignment_from_so' && isset($this->_salesorderid) && $this->_salesorderid!='') {
			// We are getting called from the RecurringConsignment cron service!
			$this->createRecurringConsignmentFromSO();

		} else if(isset($_REQUEST)) {
			if($_REQUEST['action'] != 'ConsignmentAjax' && $_REQUEST['ajxaction'] != 'DETAILVIEW'
					&& $_REQUEST['action'] != 'MassEditSave' && $_REQUEST['action'] != 'ProcessDuplicates'
					&& $_REQUEST['action'] != 'SaveAjax' && $this->isLineItemUpdate != false && $_REQUEST['action'] != 'FROM_WS') {
				//Based on the total Number of rows we will save the product relationship with this entity
				saveInventoryProductDetails($this, 'Consignment');
			} else if($_REQUEST['action'] == 'ConsignmentAjax' || $_REQUEST['action'] == 'MassEditSave' || $_REQUEST['action'] == 'FROM_WS') {
				$updateInventoryProductRel_deduct_stock = false;
			}
		}
		// Update the currency id and the conversion rate for the consignment
		$update_query = "update vtiger_consignment set currency_id=?, conversion_rate=? where consignmentid=?";

		$update_params = array($this->column_fields['currency_id'], $this->column_fields['conversion_rate'], $this->id);
		$this->db->pquery($update_query, $update_params);
	}
	
	/**
	 * Customizing the restore procedure.
	 */
	function restore($module, $id) {
		global $updateInventoryProductRel_deduct_stock;
		$status = getConsignmentStatus($id);
		if($status != 'Cancel') {
			$updateInventoryProductRel_deduct_stock = true;
		}
		parent::restore($module, $id);
	}

	/**
	 * Customizing the Delete procedure.
	 */
	function trash($module, $recordId) {
		$status = getConsignmentStatus($recordId);
		if($status != 'Cancel') {
			addProductsToStock($recordId);
		}
		parent::trash($module, $recordId);
	}	
	
	/**	function used to get the name of the current object
	 *	@return string $this->name - name of the current object
	 */
	function get_summary_text()
	{
		global $log;
		$log->debug("Entering get_summary_text() method ...");
		$log->debug("Exiting get_summary_text method ...");
		return $this->name;
	}


	/**	function used to get the list of activities which are related to the invoice
	 *	@param int $id - invoice id
	 *	@return array - return an array which will be returned from the function GetRelatedList
	 */
	function get_activities($id, $cur_tab_id, $rel_tab_id, $actions=false) {
		global $log, $singlepane_view,$currentModule,$current_user;
		$log->debug("Entering get_activities(".$id.") method ...");
		$this_module = $currentModule;

		$related_module = vtlib_getModuleNameById($rel_tab_id);
		require_once("modules/$related_module/Activity.php");
		$other = new Activity();
		vtlib_setup_modulevars($related_module, $other);
		$singular_modname = vtlib_toSingular($related_module);

		$parenttab = getParentTab();

		if($singlepane_view == 'true')
			$returnset = '&return_module='.$this_module.'&return_action=DetailView&return_id='.$id;
		else
			$returnset = '&return_module='.$this_module.'&return_action=CallRelatedList&return_id='.$id;

		$button = '';

		$button .= '<input type="hidden" name="activity_mode">';

		if($actions) {
			if(is_string($actions)) $actions = explode(',', strtoupper($actions));
			if(in_array('ADD', $actions) && isPermitted($related_module,1, '') == 'yes') {
				if(getFieldVisibilityPermission('Calendar',$current_user->id,'parent_id', 'readwrite') == '0') {
					$button .= "<input title='".getTranslatedString('LBL_NEW'). " ". getTranslatedString('LBL_TODO', $related_module) ."' class='crmbutton small create'" .
						" onclick='this.form.action.value=\"EditView\";this.form.module.value=\"$related_module\";this.form.return_module.value=\"$this_module\";this.form.activity_mode.value=\"Task\";' type='submit' name='button'" .
						" value='". getTranslatedString('LBL_ADD_NEW'). " " . getTranslatedString('LBL_TODO', $related_module) ."'>&nbsp;";
				}
			}
		}

		$userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>
							'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');
		$query = "SELECT case when (vtiger_users.user_name not like '') then $userNameSql else vtiger_groups.groupname end as user_name,
				vtiger_contactdetails.lastname, vtiger_contactdetails.firstname, vtiger_contactdetails.contactid,
				vtiger_activity.*,vtiger_seactivityrel.crmid as parent_id,vtiger_crmentity.crmid, vtiger_crmentity.smownerid,
				vtiger_crmentity.modifiedtime
				from vtiger_activity
				inner join vtiger_seactivityrel on vtiger_seactivityrel.activityid=vtiger_activity.activityid
				inner join vtiger_crmentity on vtiger_crmentity.crmid=vtiger_activity.activityid
				left join vtiger_cntactivityrel on vtiger_cntactivityrel.activityid= vtiger_activity.activityid
				left join vtiger_contactdetails on vtiger_contactdetails.contactid = vtiger_cntactivityrel.contactid
				left join vtiger_users on vtiger_users.id=vtiger_crmentity.smownerid
				left join vtiger_groups on vtiger_groups.groupid=vtiger_crmentity.smownerid
				where vtiger_seactivityrel.crmid=".$id." and activitytype='Task' and vtiger_crmentity.deleted=0
						and (vtiger_activity.status is not NULL and vtiger_activity.status != 'Completed')
						and (vtiger_activity.status is not NULL and vtiger_activity.status != 'Deferred')";

		$return_value = GetRelatedList($this_module, $related_module, $other, $query, $button, $returnset);

		if($return_value == null) $return_value = Array();
		$return_value['CUSTOM_BUTTON'] = $button;

		$log->debug("Exiting get_activities method ...");
		return $return_value;
	}

	// Function to get column name - Overriding function of base class
	function get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype) {
		if ($columname == 'salesorderid') {
			if ($fldvalue == '') return null;
		}
		return parent::get_column_value($columname, $fldvalue, $fieldname, $uitype, $datatype);
	}

	/*
	 * Function to get the secondary query part of a report
	 * @param - $module primary module name
	 * @param - $secmodule secondary module name
	 * returns the query string formed on fetching the related data for report for secondary module
	 */
	function generateReportsSecQuery($module,$secmodule,$queryPlanner){

		// Define the dependency matrix ahead
		$matrix = $queryPlanner->newDependencyMatrix();
		$matrix->setDependency('vtiger_crmentityConsignment', array('vtiger_usersConsignment', 'vtiger_groupsConsignment', 'vtiger_lastModifiedByConsignment'));
		$matrix->setDependency('vtiger_inventoryproductrelConsignment', array('vtiger_productsConsignment', 'vtiger_serviceConsignment'));

		if (!$queryPlanner->requireTable('vtiger_consignment', $matrix)) {
			return '';
		}

		$matrix->setDependency('vtiger_consignment',array('vtiger_crmentityConsignment', "vtiger_currency_info$secmodule",
				'vtiger_consignmentcf', 'vtiger_salesorderConsignment', 'vtiger_consignmentbillads',
				'vtiger_consignmentshipads', 'vtiger_inventoryproductrelConsignment', 'vtiger_contactdetailsConsignment', 'vtiger_accountConsignment'));

		$query = $this->getRelationQuery($module,$secmodule,"vtiger_consignment","consignmentid", $queryPlanner);

		if ($queryPlanner->requireTable('vtiger_crmentityConsignment', $matrix)) {
			$query .= " left join vtiger_crmentity as vtiger_crmentityConsignment on vtiger_crmentityConsignment.crmid=vtiger_consignment.consignmentid and vtiger_crmentityConsignment.deleted=0";
		}
		if ($queryPlanner->requireTable('vtiger_consignmentcf')) {
			$query .= " left join vtiger_consignmentcf on vtiger_consignment.consignmentid = vtiger_consignmentcf.consignmentid";
		}
		if ($queryPlanner->requireTable("vtiger_currency_info$secmodule")) {
			$query .= " left join vtiger_currency_info as vtiger_currency_info$secmodule on vtiger_currency_info$secmodule.id = vtiger_consignment.currency_id";
		}
		if ($queryPlanner->requireTable('vtiger_salesorderConsignment')) {
			$query .= " left join vtiger_salesorder as vtiger_salesorderConsignment on vtiger_salesorderConsignment.salesorderid=vtiger_consignment.salesorderid";
		}
		if ($queryPlanner->requireTable('vtiger_consignmentbillads')) {
			$query .= " left join vtiger_consignmentbillads on vtiger_consignment.consignmentid=vtiger_consignmentbillads.consignmentbilladdressid";
		}
		if ($queryPlanner->requireTable('vtiger_consignmentshipads')) {
			$query .= " left join vtiger_consignmentshipads on vtiger_consignment.consignmentid=vtiger_consignmentshipads.consignmentshipaddressid";
		}
		if ($queryPlanner->requireTable('vtiger_inventoryproductrelConsignment', $matrix)) {
		}
		if ($queryPlanner->requireTable('vtiger_productsConsignment')) {
			$query .= " left join vtiger_products as vtiger_productsConsignment on vtiger_productsConsignment.productid = vtiger_inventoryproductreltmpConsignment.productid";
		}
		if ($queryPlanner->requireTable('vtiger_serviceConsignment')) {
			$query .= " left join vtiger_service as vtiger_serviceConsignment on vtiger_serviceConsignment.serviceid = vtiger_inventoryproductreltmpConsignment.productid";
		}
		if ($queryPlanner->requireTable('vtiger_groupsConsignment')) {
			$query .= " left join vtiger_groups as vtiger_groupsConsignment on vtiger_groupsConsignment.groupid = vtiger_crmentityConsignment.smownerid";
		}
		if ($queryPlanner->requireTable('vtiger_usersConsignment')) {
			$query .= " left join vtiger_users as vtiger_usersConsignment on vtiger_usersConsignment.id = vtiger_crmentityConsignment.smownerid";
		}
		if ($queryPlanner->requireTable('vtiger_contactdetailsConsignment')) {
			$query .= " left join vtiger_contactdetails as vtiger_contactdetailsConsignment on vtiger_consignment.contactid = vtiger_contactdetailsConsignment.contactid";
		}
		if ($queryPlanner->requireTable('vtiger_accountConsignment')) {
			$query .= " left join vtiger_account as vtiger_accountConsignment on vtiger_accountConsignment.accountid = vtiger_consignment.accountid";
		}
		if ($queryPlanner->requireTable('vtiger_lastModifiedByConsignment')) {
			$query .= " left join vtiger_users as vtiger_lastModifiedByConsignment on vtiger_lastModifiedByConsignment.id = vtiger_crmentityConsignment.modifiedby ";
		}
		if ($queryPlanner->requireTable("vtiger_createdbyConsignment")){
			$query .= " left join vtiger_users as vtiger_createdbyConsignment on vtiger_createdbyConsignment.id = vtiger_crmentityConsignment.smcreatorid ";
		}

		//if secondary modules custom reference field is selected
        $query .= parent::getReportsUiType10Query($secmodule, $queryPlanner);
        
		return $query;
	}



	/*
	 * Function to get the relation tables for related modules 
	 * @param - $secmodule secondary module name
	 * returns the array with table names and fieldnames storing relations between module and this module
	 */
	function setRelationTables($secmodule){
		$rel_tables = array (
			"Calendar" =>array("vtiger_seactivityrel"=>array("crmid","activityid"),"vtiger_consignment"=>"consignmentid"),
			"Documents" => array("vtiger_senotesrel"=>array("crmid","notesid"),"vtiger_consignment"=>"consignmentid"),
			"Accounts" => array("vtiger_consignment"=>array("consignmentid","accountid")),
			"Contacts" => array("vtiger_consignment"=>array("consignmentid","contactid")),
		);
		return $rel_tables[$secmodule];
	}
	
	// Function to unlink an entity with given Id from another entity
	function unlinkRelationship($id, $return_module, $return_id) {
		global $log;
		if(empty($return_module) || empty($return_id)) return;

		if($return_module == 'Accounts' || $return_module == 'Contacts') {
			$this->trash('Consignment',$id);
		} elseif($return_module=='SalesOrder') {
			$relation_query = 'UPDATE vtiger_consignment set salesorderid=? where consignmentid=?';
			$this->db->pquery($relation_query, array(null,$id));
		} elseif($return_module == 'Documents') {
			$sql = 'DELETE FROM vtiger_senotesrel WHERE crmid=? AND notesid=?';
			$this->db->pquery($sql, array($id, $return_id));
		} else {
			parent::unlinkRelationship($id, $return_module, $return_id);
		}
	}

	/*
	 * Function to get the relations of salesorder to invoice for recurring invoice procedure
	 * @param - $salesorder_id Salesorder ID
	 */
	function createRecurringConsignmentFromSO(){
		global $adb;
		$salesorder_id = $this->_salesorderid;
		$query1 = "SELECT * FROM vtiger_inventoryproductrel WHERE id=?";
		$res = $adb->pquery($query1, array($salesorder_id));
		$no_of_products = $adb->num_rows($res);
		$fieldsList = $adb->getFieldsArray($res);
		$update_stock = array();
		for($j=0; $j<$no_of_products; $j++) {
			$row = $adb->query_result_rowdata($res, $j);
			$col_value = array();
			for($k=0; $k<count($fieldsList); $k++) {
				if($fieldsList[$k]!='lineitem_id'){
					$col_value[$fieldsList[$k]] = $row[$fieldsList[$k]];
				}
			}
			if(count($col_value) > 0) {
				$col_value['id'] = $this->id;
				$columns = array_keys($col_value);
				$values = array_values($col_value);
				$query2 = "INSERT INTO vtiger_inventoryproductrel(". implode(",",$columns) .") VALUES (". generateQuestionMarks($values) .")";
				$adb->pquery($query2, array($values));
				$prod_id = $col_value['productid'];
				$qty = $col_value['quantity'];
				$update_stock[$col_value['sequence_no']] = $qty;
				updateStk($prod_id,$qty,'',array(),'Consignment');
			}
		}

		$query1 = "SELECT * FROM vtiger_inventorysubproductrel WHERE id=?";
		$res = $adb->pquery($query1, array($salesorder_id));
		$no_of_products = $adb->num_rows($res);
		$fieldsList = $adb->getFieldsArray($res);
		for($j=0; $j<$no_of_products; $j++) {
			$row = $adb->query_result_rowdata($res, $j);
			$col_value = array();
			for($k=0; $k<count($fieldsList); $k++) {
					$col_value[$fieldsList[$k]] = $row[$fieldsList[$k]];
			}
			if(count($col_value) > 0) {
				$col_value['id'] = $this->id;
				$columns = array_keys($col_value);
				$values = array_values($col_value);
				$query2 = "INSERT INTO vtiger_inventorysubproductrel(". implode(",",$columns) .") VALUES (". generateQuestionMarks($values) .")";
				$adb->pquery($query2, array($values));
				$prod_id = $col_value['productid'];
				$qty = $update_stock[$col_value['sequence_no']];
				updateStk($prod_id,$qty,'',array(),'Consignment');
			}
		}

		//Adding charge values
		$adb->pquery('DELETE FROM vtiger_inventorychargesrel WHERE recordid = ?', array($this->id));
		$adb->pquery('INSERT INTO vtiger_inventorychargesrel SELECT ?, charges FROM vtiger_inventorychargesrel WHERE recordid = ?', array($this->id, $salesorder_id));

		//Update the netprice (subtotal), taxtype, discount, S&H charge, adjustment and total for the Consignment
		$updatequery  = " UPDATE vtiger_consignment SET ";
		$updateparams = array();
		// Remaining column values to be updated -> column name to field name mapping
		$consignment_column_field = Array (
			'adjustment' => 'txtAdjustment',
			'subtotal' => 'hdnSubTotal',
			'total' => 'hdnGrandTotal',
			'taxtype' => 'hdnTaxType',
			'discount_percent' => 'hdnDiscountPercent',
			'discount_amount' => 'hdnDiscountAmount',
			's_h_amount' => 'hdnS_H_Amount',
			'region_id' => 'region_id',
			's_h_percent' => 'hdnS_H_Percent',
			'balance' => 'hdnGrandTotal'
		);
		$updatecols = array();
		foreach($consignment_column_field as $col => $field) {
			$updatecols[] = "$col=?";
			$updateparams[] = $this->column_fields[$field];
		}
		if (count($updatecols) > 0) {
			$updatequery .= implode(",", $updatecols);

			$updatequery .= " WHERE consignmentid=?";
			array_push($updateparams, $this->id);

			$adb->pquery($updatequery, $updateparams);
		}
	}	


    
	function insertIntoEntityTable($table_name, $module, $fileid = '')  {
		//Ignore relation table insertions while saving of the record
		if($table_name == 'vtiger_inventoryproductrel') {
			return;
		}
		parent::insertIntoEntityTable($table_name, $module, $fileid);
	}

	/*Function to create records in current module.
	**This function called while importing records to this module*/
	function createRecords($obj) {
		$createRecords = createRecords($obj);
		return $createRecords;
	}

	/*Function returns the record information which means whether the record is imported or not
	**This function called while importing records to this module*/
	function importRecord($obj, $inventoryFieldData, $lineItemDetails) {
		$entityInfo = importRecord($obj, $inventoryFieldData, $lineItemDetails);
		return $entityInfo;
	}

	/*Function to return the status count of imported records in current module.
	**This function called while importing records to this module*/
	function getImportStatusCount($obj) {
		$statusCount = getImportStatusCount($obj);
		return $statusCount;
	}

	function undoLastImport($obj, $user) {
		$undoLastImport = undoLastImport($obj, $user);
	}

        //  begin global search for Consignments  
        function getListQuery($module, $usewhere='') {
                global $current_user;

                $query = "SELECT vtiger_crmentity.*,
			vtiger_consignment.*,
			vtiger_consignmentbillads.*,
			vtiger_consignmentshipads.*,
			vtiger_salesorder.subject AS salessubject,
			vtiger_account.accountname,
			vtiger_currency_info.currency_name
			FROM vtiger_consignment
			INNER JOIN vtiger_crmentity
				ON vtiger_crmentity.crmid = vtiger_consignment.consignmentid
			INNER JOIN vtiger_consignmentbillads
				ON vtiger_consignment.consignmentid = vtiger_consignmentbillads.consignmentbilladdressid
			INNER JOIN vtiger_consignmentshipads
				ON vtiger_consignment.consignmentid = vtiger_consignmentshipads.consignmentshipaddressid
			LEFT JOIN vtiger_currency_info
				ON vtiger_consignment.currency_id = vtiger_currency_info.id
			LEFT OUTER JOIN vtiger_salesorder
				ON vtiger_salesorder.salesorderid = vtiger_consignment.salesorderid
			LEFT OUTER JOIN vtiger_account
			        ON vtiger_account.accountid = vtiger_consignment.accountid
			LEFT JOIN vtiger_contactdetails
				ON vtiger_contactdetails.contactid = vtiger_consignment.contactid
			INNER JOIN vtiger_consignmentcf
				ON vtiger_consignment.consignmentid = vtiger_consignmentcf.consignmentid
			LEFT JOIN vtiger_groups
				ON vtiger_groups.groupid = vtiger_crmentity.smownerid
			LEFT JOIN vtiger_users
				ON vtiger_users.id = vtiger_crmentity.smownerid";
		$query .= getNonAdminAccessControlQuery($module,$current_user);
		$query .= "WHERE vtiger_crmentity.deleted = 0 ".$where;

                return $query;
        }	
	
	/** Function to export the lead records in CSV Format
	* @param reference variable - where condition is passed when the query is executed
	* Returns Export Consignment Query.
	*/
	function create_export_query($where)
	{
		global $log;
		global $current_user;
		$log->debug("Entering create_export_query(".$where.") method ...");

		include("include/utils/ExportUtils.php");

		//To get the Permitted fields query and the permitted fields list
		$sql = getPermittedFieldsQuery("Consignment", "detail_view");
		$fields_list = getFieldsListFromQuery($sql);
		$fields_list .= getInventoryFieldsForExport($this->table_name);
		$userNameSql = getSqlForNameInDisplayFormat(array('first_name'=>'vtiger_users.first_name', 'last_name' => 'vtiger_users.last_name'), 'Users');

		$query = "SELECT $fields_list FROM ".$this->entity_table."
				INNER JOIN vtiger_consignment ON vtiger_consignment.consignmentid = vtiger_crmentity.crmid
				LEFT JOIN vtiger_consignmentcf ON vtiger_consignmentcf.consignmentid = vtiger_consignment.consignmentid
				LEFT JOIN vtiger_salesorder ON vtiger_salesorder.salesorderid = vtiger_consignment.salesorderid
				LEFT JOIN vtiger_consignmentbillads ON vtiger_consignmentbillads.consignmentbilladdressid = vtiger_consignment.consignmentid
				LEFT JOIN vtiger_consignmentshipads ON vtiger_consignmentshipads.consignmentshipaddressid = vtiger_consignment.consignmentid
				LEFT JOIN vtiger_inventoryproductrel ON vtiger_inventoryproductrel.id = vtiger_consignment.consignmentid
				LEFT JOIN vtiger_products ON vtiger_products.productid = vtiger_inventoryproductrel.productid
				LEFT JOIN vtiger_service ON vtiger_service.serviceid = vtiger_inventoryproductrel.productid
				LEFT JOIN vtiger_contactdetails ON vtiger_contactdetails.contactid = vtiger_consignment.contactid
				LEFT JOIN vtiger_account ON vtiger_account.accountid = vtiger_consignment.accountid
				LEFT JOIN vtiger_currency_info ON vtiger_currency_info.id = vtiger_consignment.currency_id
				LEFT JOIN vtiger_groups ON vtiger_groups.groupid = vtiger_crmentity.smownerid
				LEFT JOIN vtiger_users ON vtiger_users.id = vtiger_crmentity.smownerid";

		$query .= $this->getNonAdminAccessControlQuery('Consignment',$current_user);
		$where_auto = " vtiger_crmentity.deleted=0";

		if($where != "") {
			$query .= " where ($where) AND ".$where_auto;
		} else {
			$query .= " where ".$where_auto;
		}

		$log->debug("Exiting create_export_query method ...");
		return $query;
	}

	/**
	 * Function to get importable mandatory fields
	 * By default some fields like Quantity, List Price is not mandaroty for Invertory modules but
	 * import fails if those fields are not mapped during import.
	 */
	function getMandatoryImportableFields() {
		return getInventoryImportableMandatoryFeilds($this->moduleName);
	}	
		
 	/**
	* Invoked when special actions are performed on the module.
	* @param String Module name
	* @param String Event Type
	*/
	function vtlib_handler($moduleName, $eventType) {
		require_once('include/utils/utils.php');
		include_once('vtlib/Vtiger/Module.php');
		global $adb;

 		if($eventType == 'module.postinstall') {


			// Mark the module as Standard module
			$adb->pquery('UPDATE vtiger_tab SET customized=0 WHERE name=?', array($moduleName));
			$consignmentInstance = Vtiger_Module::getInstance('Consignment');
			
            //  link Salesorder			
			$salesorderInstance = Vtiger_Module::getInstance('SalesOrder');
			$salesorderInstance->setRelatedlist($consignmentInstance,'Consignment',array('ADD'),'get_dependents_list');
            $salesorderInstance->addLink('DETAILVIEWBASIC', 'LBL_SALESORDER_ADD_CONSIGNMENT',
                    'index.php?module=Consignment&view=Edit&sourceModule=$MODULE$&sourceRecord=$RECORD$&salesorder_id=$RECORD$&relationOperation=true');
					
            //  link Accounts
            $accountsInstance = Vtiger_Module::getInstance('Accounts');
            $accountsInstance->addLink('DETAILVIEWBASIC', 'LBL_ACCOUNTS_ADD_CONSIGNMENT',
                    'index.php?module=Consignment&action=EditView&return_module=Accounts&return_action=DetailView&convertmode=acctoconsignment&createmode=link&return_id=$RECORD$&account_id=$RECORD$&parenttab=Sales',
                    'themes/images/actionGenerateInvoice.gif');
            $accountsInstance->setRelatedlist($consignmentInstance,'Consignment',array('ADD'),'get_dependents_list');
            
            //  link Contacts
            $contactsInstance = Vtiger_Module::getInstance('Contacts');
            $contactsInstance->addLink('DETAILVIEWBASIC', 'LBL_CONTACTS_ADD_CONSIGNMENT',
                    'index.php?module=Consignment&action=EditView&return_module=Contacts&return_action=DetailView&convertmode=contoconsignment&createmode=link&return_id=$RECORD$&contact_id=$RECORD$&parenttab=Sales',
                    'themes/images/actionGenerateInvoice.gif');
            $contactsInstance->setRelatedlist($consignmentInstance,'Consignment',array('ADD'),'get_dependents_list');

			// 添加评论模块Add Project module to the related list of ModComment module            
			$modcommentsModuleInstance = Vtiger_Module::getInstance('ModComments');
			if($modcommentsModuleInstance && file_exists('modules/ModComments/ModComments.php')) {
				include_once 'modules/ModComments/ModComments.php';
				if(class_exists('ModComments')) ModComments::addWidgetTo(array('Consignment'));
			}
            //配置consignment_no
            $modFocus = CRMEntity::getInstance('Consignment');
            $modFocus->setModuleSeqNumber('configure', 'Consignment', '', '1');

		} else if($eventType == 'module.disabled') {
			$consignmentInstance = Vtiger_Module::getInstance('Consignment');
			
            //  unlink Salesorder			
			$salesorderInstance = Vtiger_Module::getInstance('SalesOrder');
			$salesorderInstance->unsetRelatedlist($consignmentInstance,'Consignment','get_dependents_list');
            $salesorderInstance->deleteLink('DETAILVIEWBASIC', 'LBL_SALESORDER_ADD_CONSIGNMENT');			
			
            //  unlink Accounts
            $accountsInstance = Vtiger_Module::getInstance('Accounts');
            $accountsInstance->deleteLink('DETAILVIEWBASIC', 'LBL_ACCOUNTS_ADD_CONSIGNMENT');         
            $accountsInstance->unsetRelatedlist($consignmentInstance,'Consignment','get_dependents_list');
			
            //  unlink Contacts
            $contactsInstance = Vtiger_Module::getInstance('Contacts');
            $contactsInstance->deleteLink('DETAILVIEWBASIC', 'LBL_CONTACTS_ADD_CONSIGNMENT');         
            $contactsInstance->unsetRelatedlist($consignmentInstance,'Consignment','get_dependents_list');			
            
		} else if($eventType == 'module.enabled') {
			$consignmentInstance = Vtiger_Module::getInstance('Consignment');
            //  link Salesorder			
			$salesorderInstance = Vtiger_Module::getInstance('SalesOrder');
			$salesorderInstance->setRelatedlist($consignmentInstance,'Consignment',array('ADD'),'get_dependents_list');
            $salesorderInstance->addLink('DETAILVIEWBASIC', 'LBL_SALESORDER_ADD_CONSIGNMENT',
                    'index.php?module=Consignment&view=Edit&sourceModule=$MODULE$&sourceRecord=$RECORD$&salesorder_id=$RECORD$&relationOperation=true');
					
            //  link Accounts
            $accountsInstance = Vtiger_Module::getInstance('Accounts');
            $accountsInstance->addLink('DETAILVIEWBASIC', 'LBL_ACCOUNTS_ADD_CONSIGNMENT',
                    'index.php?module=Consignment&action=EditView&return_module=Accounts&return_action=DetailView&convertmode=acctoconsignment&createmode=link&return_id=$RECORD$&account_id=$RECORD$&parenttab=Sales',
                    'themes/images/actionGenerateInvoice.gif');
            $accountsInstance->setRelatedlist($consignmentInstance,'Consignment',array('ADD'),'get_dependents_list');
            
            //  link Contacts
            $contactsInstance = Vtiger_Module::getInstance('Contacts');
            $contactsInstance->addLink('DETAILVIEWBASIC', 'LBL_CONTACTS_ADD_CONSIGNMENT',
                    'index.php?module=Consignment&action=EditView&return_module=Contacts&return_action=DetailView&convertmode=contoconsignment&createmode=link&return_id=$RECORD$&contact_id=$RECORD$&parenttab=Sales',
                    'themes/images/actionGenerateInvoice.gif');
            $contactsInstance->setRelatedlist($consignmentInstance,'Consignment',array('ADD'),'get_dependents_list');
            
		} else if($eventType == 'module.preuninstall') {
		// TODO Handle actions when this module is about to be deleted.
		} else if($eventType == 'module.preupdate') {
		// TODO Handle actions before this module is updated.
		} else if($eventType == 'module.postupdate') {
            $consignmentInstance = Vtiger_Module::getInstance('Consignment');
            //  link Salesorder			
			$salesorderInstance = Vtiger_Module::getInstance('SalesOrder');
			$salesorderInstance->setRelatedlist($consignmentInstance,'Consignment',array('ADD'),'get_dependents_list');
					
            //  link Accounts
            $accountsInstance = Vtiger_Module::getInstance('Accounts');
            $accountsInstance->setRelatedlist($consignmentInstance,'Consignment',array('ADD'),'get_dependents_list');
            
            //  link Contacts
            $contactsInstance = Vtiger_Module::getInstance('Contacts');
            $contactsInstance->setRelatedlist($consignmentInstance,'Consignment',array('ADD'),'get_dependents_list');
            
            
		}
 	}
        


}

?>